package com.baosight.risk.service.fltd.impl;

import com.alibaba.fastjson.JSON;
import com.baosight.risk.api.fltd.FltdPressService;
import com.baosight.risk.api.fltd.FltdProcessService;
import com.baosight.risk.api.fltd.FltdTaskService;
import com.baosight.risk.common.aspects.factory.AsyncFactory;
import com.baosight.risk.common.bean.BeanUtils;
import com.baosight.risk.common.email.service.EmailService;
import com.baosight.risk.common.manager.AsyncManager;
import com.baosight.risk.common.utils.DateUtils;
import com.baosight.risk.common.utils.ReadProperties;
import com.baosight.risk.common.utils.ShiroUtils;
import com.baosight.risk.common.utils.StringUtils;
import com.baosight.risk.mapper.fltd.FltdPressMapper;
import com.baosight.risk.service.fltd.entity.FltdPress;
import com.baosight.risk.service.fltd.entity.FltdTask;
import com.baosight.risk.service.fltd.vo.FltdPressVO;
import com.baosight.risk.service.fltd.vo.FltdTaskVO;
import com.baosight.risk.service.system.entity.SysOperLog;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 作者： lishaoqingiiiiiiiiiiiiiiii
 * 时间： 2019年09月25日
 * 描述： FltdPressServiceImpl
 * 版本: v1.0
 */
@Service
public class FltdPressServiceImpl implements FltdPressService {

    @Autowired
    private FltdPressMapper fltdPressMapper;

    @Autowired
    private EmailService emailService;

    @Autowired
    private FltdTaskService fltdTaskService;

    @Autowired
    private FltdProcessService fltdProcessService;

    @Override
    public int insert(FltdPress fltdPress) {
        return fltdPressMapper.insert(fltdPress);
    }

    @Override
    public int deleteUrgent(String flowNo, String nodeCode) {
        return fltdPressMapper.deleteUrgent(flowNo, nodeCode);
    }

    @Override
    public List<FltdPressVO> queryAll(String procGuid) {
        return fltdPressMapper.queryAll(procGuid);
    }

    @Override
    public void createUrgent(FltdPress fltdPress) throws Exception {
        String subject = fltdPress.getExt1();
        String message = fltdPress.getExt2();
//        int status = emailService.sendEmail("lishaoqing", subject, message, null);
        //int status = emailService.sendEmail(fltdPress.getPressUserCode(), subject, message, null);
        //String checkProd = ReadProperties.getValueString("jdbc.password");

        int status = emailService.sendEmail(fltdPress.getCurrUserCode(), subject, message, null);

        //邮件发送失败
        if (status != 1) {
            throw new Exception("催办发送失败");
        }

        int currentPressNum = fltdPress.getPressNum() == null ? 1 : fltdPress.getPressNum() + 1;
        BeanUtils.initBean(fltdPress);
        BeanUtils.initExt(fltdPress);
        fltdPress.setExt1(subject);
        fltdPress.setExt2(message);
        fltdPress.setUpdateBy(null);
        fltdPress.setUpdateTime(null);
        fltdPress.setPressGuid(UUID.randomUUID().toString());
        fltdPress.setPressUserCode(ShiroUtils.getUser().getUserCode());
        fltdPress.setPressUserName(ShiroUtils.getUser().getUserDesc());
        fltdPress.setPressDate(new Date());
        fltdPress.setPressNum(currentPressNum);
        fltdPress.setRemark("发送状态："+ status);
        int insert = fltdPressMapper.insert(fltdPress);
        if (insert == 0) {
            throw new Exception("催办发送失败");
        }

        FltdTask updateTask = new FltdTask();
        updateTask.setTodoGuid(fltdPress.getTodoGuid());
        updateTask.setPressNum(currentPressNum);
        int i = fltdTaskService.updateTaskStatus(updateTask);
        if (i == 0) {
            throw new Exception("催办发送失败");
        }

    }

    @Override
    public void doUrgent(String jobId) throws Exception {
        List<SysOperLog> logs = new ArrayList<>();
        Exception error = null;
        try {
            List<FltdTask> urgentTasks = fltdTaskService.selectUrgentTask();
            Map<String, Map<String, Object>> urgentMap = convertUrgentTasks(urgentTasks);
            // 给每个人发送催办邮件提醒
            for (String userCode : urgentMap.keySet()) {
                Map<String, Object> taskMap = urgentMap.get(userCode);
                List<String> nameList = (List<String>)taskMap.get("nameList");
                StringBuilder sb = new StringBuilder();
                for (String bizDesc : nameList) {
                    sb.append("\t").append(bizDesc).append("\n");
                }
                String subject = "催办提醒-全面风险管理系统";
                String message = "您有如下待办未处理：\n" + sb.toString() + "请及时处理，谢谢！\n\n\n本邮件属系统邮件，请勿回复。";
//                int status = emailService.sendEmail("lishaoqing", subject, message, null);
                // 发送邮件
                int status = emailService.sendEmail(userCode, subject, message, null);

                // 添加催办日志，更新催办数量
                List<FltdTask> taskList = (List<FltdTask>)taskMap.get("taskList");
                for (FltdTask task : taskList) {
                    int currentPressNum = task.getPressNum() == null ? 1 : task.getPressNum() + 1;
                    FltdPress fltdPress = (FltdPress) BeanUtils.initBean(new FltdPress());
                    BeanUtils.copyBeanProp(fltdPress, task);
                    BeanUtils.initExt(fltdPress);
                    fltdPress.setUpdateBy(null);
                    fltdPress.setUpdateTime(null);
                    fltdPress.setPressGuid(UUID.randomUUID().toString());
                    fltdPress.setPressUserCode("admin");
                    fltdPress.setPressUserName("系统管理员");
                    fltdPress.setPressDate(new Date());
                    fltdPress.setPressNum(currentPressNum);
                    fltdPress.setRemark("发送状态："+ status);
                    int insert = fltdPressMapper.insert(fltdPress);
                    if (insert == 0) {
                        throw new Exception("催办发送异常， 催办日志表操作异常！");
                    }

                    FltdTask updateTask = new FltdTask();
                    updateTask.setTodoGuid(task.getTodoGuid());
                    updateTask.setPressNum(currentPressNum);
                    int i = fltdTaskService.updateTaskStatus(updateTask);
                    if (i == 0) {
                        throw new Exception("催办发送异常， 待办任务表操作异常！");
                    }
                }

            }


//            for (FltdTask task : urgentTasks) {
//                //发送邮件
//                String subject = "催办提醒-全面风险管理系统";
//                String message = "您有一条催办提醒，待办名称：" +task.getBizDesc() + "请在"+ DateUtils.formatYYYY_MM_DD(task.getPlanEndDate())+"之前完成！";
//                int status = emailService.sendEmail("lishaoqing", subject, message, null);
////            int status = emailService.sendEmail(task.getCurrUserCode(), subject, message, null);
//
//                int currentPressNum = task.getPressNum() == null ? 0 : task.getPressNum() + 1;
//                FltdPress fltdPress = (FltdPress) BeanUtils.initBean(new FltdPress());
//                BeanUtils.copyBeanProp(fltdPress, task);
//                BeanUtils.initExt(fltdPress);
//                fltdPress.setUpdateBy(null);
//                fltdPress.setUpdateTime(null);
//                fltdPress.setPressGuid(UUID.randomUUID().toString());
//                fltdPress.setPressUserCode("admin");
//                fltdPress.setPressUserName("系统管理员");
//                fltdPress.setPressDate(new Date());
//                fltdPress.setPressNum(currentPressNum);
//                fltdPress.setRemark("发送状态："+ status);
//                int insert = fltdPressMapper.insert(fltdPress);
//                if (insert == 0) {
//                    throw new Exception("催办发送异常， 数据库操作异常！");
//                }
//
//                FltdTask updateTask = new FltdTask();
//                updateTask.setTodoGuid(task.getTodoGuid());
//                updateTask.setPressNum(currentPressNum);
//                int i = fltdTaskService.updateTaskStatus(updateTask);
//                if (i == 0) {
//                    throw new Exception("催办发送异常， 数据库操作异常！");
//                }
//            }
            logs.add(fltdProcessService.getLog("工作流催办定时任务执行成功", 0, "", jobId));
        } catch (Exception e) {
            error = e;
            logs.add(fltdProcessService.getLog("工作流催办定时任务执行失败", 1, e.getMessage(), jobId));
        }
        // 保存日志到数据库
        AsyncManager.me().execute(AsyncFactory.batchRecordOper(logs));
        if (error != null) {
            throw error;
        }
    }

    /**
     * 合并显示所有待办，取出待办名称
     *
     */
    @Override
    public Map<String, Map<String, Object>> convertUrgentTasks(List<FltdTask> urgentTasks) throws Exception {
        Map<String, Map<String, Object>> result = new HashMap<>();

        // 筛选出每个人的待办
        for (FltdTask urgentTask : urgentTasks) {
            if (result.containsKey(urgentTask.getCurrUserCode())) {
                Map<String, Object> taskMap = result.get(urgentTask.getCurrUserCode());
                List<FltdTask> taskList = (List<FltdTask>)taskMap.get("taskList");
                taskList.add(urgentTask);
            } else {
                List<FltdTask> taskList = new ArrayList<>();
                taskList.add(urgentTask);
                Map<String, Object> taskMap = new HashMap<>();
                taskMap.put("taskList", taskList);
                result.put(urgentTask.getCurrUserCode(), taskMap);
            }
        }

        // 每个人的待办进行汇总合并
        for (String userCode : result.keySet()) {
            Map<String, Object> taskMap = result.get(userCode);
            List<FltdTask> taskList = (List<FltdTask>)taskMap.get("taskList");
            Map<String, Integer> groupedMap = new HashMap<>();
            List<String> nameList = new ArrayList<>();
            taskMap.put("nameList", nameList);
            for (FltdTask fltdTask : taskList) {
                if ("Y".equals(fltdTask.getGroupFlag())) {
                    String key = fltdTask.getFlowNo() + fltdTask.getNodeCode() + fltdTask.getGroupCondition();
                    if (!groupedMap.containsKey(key)) {
                        groupedMap.put(key, 1);
                        String bizDesc = "";
                        if (StringUtils.isNotEmpty(fltdTask.getAcctYear())) {
                            bizDesc = bizDesc + fltdTask.getAcctYear() + "年度";
                        }
                        if (StringUtils.isNotEmpty(fltdTask.getQuarterName())) {
                            bizDesc = bizDesc + fltdTask.getQuarterName();
                        }
                        bizDesc = bizDesc + fltdTask.getManageCompName()  + fltdTask.getFlowName();
                        nameList.add(bizDesc);
                    } else {
                        groupedMap.put(key, groupedMap.get(key) + 1);
                    }
                } else {
                    nameList.add(fltdTask.getBizDesc());
                }
            }
        }
        return result;
    }

    @Override
    public void createUrgents(List<Map> fltdPresss,String str1,String str2) throws Exception {
        for(Map fltdPres : fltdPresss){

            ObjectMapper objectMapper = new ObjectMapper();

//            objectMapper.convertValue(Object fltdPresss, <T> FltdPress);
//            FltdPress fltdPress= objectMapper.convertValue(fltdPres,FltdPress.class);
            FltdPress fltdPress = JSON.parseObject(JSON.toJSONString(fltdPres), FltdPress.class);

            String subject = str1;
            String message = str2;

//        int status = emailService.sendEmail("lishaoqing", subject, message, null);
//            int status = emailService.sendEmail(fltdPress.getPressUserCode(), subject, message, null);
            //int status = emailService.sendEmail(ShiroUtils.getUser().getUserCode(), subject, message, null);
            String checkProd = ReadProperties.getValueString("jdbc.password");
            int status = emailService.sendEmail(fltdPress.getCurrUserCode(), subject, message, null);

            //邮件发送失败
            if (status != 1) {
                throw new Exception("催办发送失败");
            }

            int currentPressNum = fltdPress.getPressNum() == null ? 1 : fltdPress.getPressNum() + 1;
            BeanUtils.initBean(fltdPress);
            BeanUtils.initExt(fltdPress);
            fltdPress.setExt1(subject);
            fltdPress.setExt2(message);
            fltdPress.setUpdateBy(null);
            fltdPress.setUpdateTime(null);
            fltdPress.setPressGuid(UUID.randomUUID().toString());
            fltdPress.setPressUserCode(ShiroUtils.getUser().getUserCode());
            fltdPress.setPressUserName(ShiroUtils.getUser().getUserDesc());
            fltdPress.setPressDate(new Date());
            fltdPress.setPressNum(currentPressNum);
            fltdPress.setRemark("发送状态："+ status);
            int insert = fltdPressMapper.insert(fltdPress);
            if (insert == 0) {
                throw new Exception("催办发送失败");
            }

            FltdTask updateTask = new FltdTask();
            updateTask.setTodoGuid(fltdPress.getTodoGuid());
            updateTask.setPressNum(currentPressNum);
            int i = fltdTaskService.updateTaskStatus(updateTask);
            if (i == 0) {
                throw new Exception("催办发送失败");
            }
        }
    }


    @Override
    public void expertUrgents(List<Map> fltdPresss,String str1,String str2) throws Exception {
        for(Map fltdPres : fltdPresss){

            ObjectMapper objectMapper = new ObjectMapper();

//            objectMapper.convertValue(Object fltdPresss, <T> FltdPress);
//            FltdPress fltdPress= objectMapper.convertValue(fltdPres,FltdPress.class);
            FltdPress fltdPress = JSON.parseObject(JSON.toJSONString(fltdPres), FltdPress.class);

            String subject = str1;
            String message = str2;

//        int status = emailService.sendEmail("lishaoqing", subject, message, null);
//            int status = emailService.sendEmail(fltdPress.getPressUserCode(), subject, message, null);
            int status = emailService.sendEmail(ShiroUtils.getUser().getUserCode(), subject, message, null);

            //邮件发送失败
            if (status != 1) {
                throw new Exception("催办发送失败");
            }

            int currentPressNum = fltdPress.getPressNum() == null ? 1 : fltdPress.getPressNum() + 1;
            BeanUtils.initBean(fltdPress);
            BeanUtils.initExt(fltdPress);
            fltdPress.setExt1(subject);
            fltdPress.setExt2(message);
            fltdPress.setUpdateBy(null);
            fltdPress.setUpdateTime(null);
            fltdPress.setPressGuid(UUID.randomUUID().toString());
            fltdPress.setPressUserCode(ShiroUtils.getUser().getUserCode());
            fltdPress.setPressUserName(ShiroUtils.getUser().getUserDesc());
            fltdPress.setPressDate(new Date());
            fltdPress.setPressNum(currentPressNum);
            fltdPress.setRemark("发送状态："+ status);
            int insert = fltdPressMapper.insert(fltdPress);
            if (insert == 0) {
                throw new Exception("催办发送失败");
            }

            FltdTask updateTask = new FltdTask();
            updateTask.setTodoGuid(fltdPress.getTodoGuid());
            updateTask.setPressNum(currentPressNum);
            int i = fltdTaskService.updateTaskStatus(updateTask);
            if (i == 0) {
                throw new Exception("催办发送失败");
            }
        }
    }

    @Override
    public void createFinishUrgents(List<Map> fltdPresss, String str1, String str2) throws Exception {
        for(Map fltdPres : fltdPresss){

            ObjectMapper objectMapper = new ObjectMapper();

//            objectMapper.convertValue(Object fltdPresss, <T> FltdPress);
//            FltdPress fltdPress= objectMapper.convertValue(fltdPres,FltdPress.class);
            FltdPress fltdPress = JSON.parseObject(JSON.toJSONString(fltdPres), FltdPress.class);

            String subject = str1;
            String message = str2;

//        int status = emailService.sendEmail("lishaoqing", subject, message, null);
//            int status = emailService.sendEmail(fltdPress.getPressUserCode(), subject, message, null);
            int status = emailService.sendEmail(fltdPress.getCurrUserCode(), subject, message, null);

            //邮件发送失败
            if (status != 1) {
                throw new Exception("催办发送失败");
            }

            int currentPressNum = fltdPress.getPressNum() == null ? 1 : fltdPress.getPressNum() + 1;
            BeanUtils.initBean(fltdPress);
            BeanUtils.initExt(fltdPress);
            fltdPress.setExt1(subject);
            fltdPress.setExt2(message);
            fltdPress.setUpdateBy(null);
            fltdPress.setUpdateTime(null);
            String pressGuid = UUID.randomUUID().toString();
            fltdPress.setPressGuid(pressGuid);
            fltdPress.setPressUserCode(ShiroUtils.getUser().getUserCode());
            fltdPress.setPressUserName(ShiroUtils.getUser().getUserDesc());
            fltdPress.setPressDate(new Date());
            fltdPress.setPressNum(currentPressNum);
            fltdPress.setRemark("发送状态："+ status);
            int insert = fltdPressMapper.insert(fltdPress);
            if (insert == 0) {
                throw new Exception("催办发送失败");
            }

            FltdTask updateTask = new FltdTask();

            //把催办次数这里注释掉了    那么前端催办不论已发布或者未发布都可以催办
            //updateTask.setTodoGuid(fltdPress.getTodoGuid());
            //updateTask.setPressNum(currentPressNum);
            //int i = fltdTaskService.updateTaskStatus(updateTask);
//            if (i == 0) {
//                throw new Exception("催办发送失败");
//            }
        }
    }

    //专家组催办
    @Override
    public void expertUrgent(List<Map> fltdPresss,String str1,String str2) throws Exception {
        for(Map fltdPres : fltdPresss){

            ObjectMapper objectMapper = new ObjectMapper();

//            objectMapper.convertValue(Object fltdPresss, <T> FltdPress);
//            FltdPress fltdPress= objectMapper.convertValue(fltdPres,FltdPress.class);
            FltdPress fltdPress = JSON.parseObject(JSON.toJSONString(fltdPres), FltdPress.class);

            String subject = str1;
            String message = str2;

//        int status = emailService.sendEmail("lishaoqing", subject, message, null);
//            int status = emailService.sendEmail(fltdPress.getPressUserCode(), subject, message, null);
            int status = emailService.sendEmail(fltdPress.getCurrUserCode(), subject, message, null);

            //邮件发送失败
//            if (status != 1) {
//                throw new Exception("催办发送失败");
//            }

            int currentPressNum = fltdPress.getPressNum() == null ? 1 : fltdPress.getPressNum() + 1;
            BeanUtils.initBean(fltdPress);
            BeanUtils.initExt(fltdPress);
            fltdPress.setExt1(subject);
            fltdPress.setExt2(message);
            fltdPress.setUpdateBy(null);
            fltdPress.setUpdateTime(null);
            fltdPress.setPressGuid(UUID.randomUUID().toString());
            fltdPress.setPressUserCode(ShiroUtils.getUser().getUserCode());
            fltdPress.setPressUserName(ShiroUtils.getUser().getUserDesc());
            fltdPress.setPressDate(new Date());
            fltdPress.setPressNum(currentPressNum);
            fltdPress.setRemark("发送状态："+ status);
//            int insert = fltdPressMapper.insert(fltdPress);
//            if (insert == 0) {
//                throw new Exception("催办发送失败");
//            }

//            FltdTask updateTask = new FltdTask();
//            updateTask.setTodoGuid(fltdPress.getTodoGuid());
//            updateTask.setPressNum(currentPressNum);
//            int i = fltdTaskService.updateTaskStatus(updateTask);
//            if (i == 0) {
//                throw new Exception("催办发送失败");
//            }
        }
    }

}
